use crate::model::file_node::FileNode;
use fltk::enums::{Align, Event};
use fltk::group::{Group, Pack, PackType};
use fltk::table::{Table, TableContext};
use fltk::{button, output, prelude::*, table, window::Window};
use lazy_static::lazy_static;
use std::cell::RefCell;
use std::future::IntoFuture;
use std::rc::Rc;



lazy_static!(
    static ref titles: [&'static str; 3] = ["name", "size", "type"];
);


pub struct HomeUi {
    file_table: Option<Table>,
    current_file_node: Option<Rc<RefCell<FileNode>>>,
}

impl HomeUi {
    pub(crate) fn init(&mut self) {
        let mut wind = Window::default()
            .with_size(800, 600)
            .center_screen()
            .with_label("教二楼");

        let group = self.create_address_bar();
        let table = self.create_file_list(&group);

        wind.end();
        wind.show();

        self.file_table = Some(table);

    }
}


impl HomeUi {
    pub(crate) fn new() -> Self {
        HomeUi {
            file_table: None,
            current_file_node: None
        }
    }

    fn say(&mut self) {
        println!("say")
    }


    pub fn render(&mut self, root: Rc<RefCell<FileNode>>) {
        self.current_file_node = Some(root.clone());

        let len = titles.len() as i32;
        let children = root.borrow().children.clone();


        self.file_table.clone().unwrap().set_rows(root.borrow().children.len() as i32 + 1); // 设置行数
        self.file_table.clone().unwrap().set_cols(len); // 设置列数
        self.file_table.clone().unwrap().draw_cell(move |_table, ctx, row, col, x, y, w, h| {
            match ctx {
                fltk::table::TableContext::Cell => {
                    // 绘制单元格
                    fltk::draw::draw_box(fltk::enums::FrameType::FlatBox, x, y, w, h, fltk::enums::Color::White);
                    fltk::draw::set_draw_color(fltk::enums::Color::Black);
                    let mut text = format!("R{}C{}", row, col);
                    if (row == 0) {
                        let i = col as usize;
                        text = titles.get(i).unwrap().to_string();
                    } else {
                        let file_node = children.get(row as usize - 1).unwrap();
                        text = match col {
                            0 => file_node.borrow().filename.to_string(),
                            1 => file_node.borrow().size.to_string(),
                            2 => "文件".to_string(),
                            _ => "-".to_string(),
                        };
                    }
                    fltk::draw::draw_text2(&text, x, y, w, h, Align::Center);
                }
                _ => {}
            }
        });
    }


    fn create_address_bar(&mut self) -> Group {
        let group = Group::default().with_size(800, 30);
        let mut pack = Pack::default_fill();
        pack.set_type(PackType::Horizontal);
        let button1 = button::Button::new(0,0,30, 30, "werwt");

        let mut output = output::Output::default_fill();
        output.set_value("You can't edit this!");
        pack.end();
        group.end();

        group
    }


    fn create_file_list<W: WidgetExt>(&mut self, group: &W) -> Table {
        let mut table = table::Table::default()
            .with_size(800, 600 - group.height())
            .below_of(group, 0);

        table.end();

        let mut self_ref = self as *mut Self;
        table.set_callback(move |tb| {
            unsafe {
                if tb.callback_context() == TableContext::Cell {
                    if let Some(self_ref) = self_ref.as_mut() {
                        let index = (tb.callback_row() - 1) as usize;
                        if let Some(option) = self_ref.current_file_node.clone().unwrap().borrow().children.get(index) {
                            self_ref.render(option.clone());
                        }
                        println!("Clicked cell: Row {}, Column {}", tb.callback_row(), tb.callback_col());
                    }
                }
            }
        });



        // table.handle(move |tb, ev| {
        //     match ev {
        //         // 鼠标点击事件
        //         Event::Push => {
        //             if tb.callback_context() == TableContext::Cell {
        //                 println!("Clicked cell: Row {}, Column {}", tb.callback_row(), tb.callback_col());
        //                 tb.redraw();
        //
        //                 // &self.say();
        //             }
        //             false
        //         }
        //         _ => true,
        //     }
        // });

        table
    }
}


